/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */
package com.iwindplus.mgt.server.service.power.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.mgt.domain.dto.power.OrgAuditDTO;
import com.iwindplus.mgt.domain.vo.power.OrgAuditVO;
import com.iwindplus.mgt.server.mapper.power.OrgAuditMapper;
import com.iwindplus.mgt.server.model.power.OrgAuditDO;
import com.iwindplus.mgt.server.service.power.OrgAuditService;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 组织审核业务层接口实现类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Service
@CacheConfig(cacheNames = {"orgAudit"})
@Transactional(rollbackFor = Exception.class)
public class OrgAuditServiceImpl extends JoinCrudRepository<OrgAuditMapper, OrgAuditDO> implements OrgAuditService {

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"orgAudit"}, allEntries = true),
            @CacheEvict(cacheNames = {"org"}, allEntries = true)
        }
    )
    @Override
    public boolean save(OrgAuditDTO entity) {
        OrgAuditVO data = super.baseMapper.selectNewestByOrgId(entity.getOrgId());
        if (Objects.nonNull(data) && entity.getAuditStatus().equals(data.getAuditStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        entity.setSeq(this.getNextSeq(entity.getOrgId()));
        String remark = CharSequenceUtil.isNotBlank(entity.getRemark()) ? entity.getRemark() : entity.getAuditStatus().getDesc();
        entity.setRemark(remark);
        final OrgAuditDO model = BeanUtil.copyProperties(entity, OrgAuditDO.class);
        super.save(model);
        entity.setId(model.getId());
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"orgAudit"}, allEntries = true),
            @CacheEvict(cacheNames = {"org"}, allEntries = true)
        }
    )
    @Override
    public boolean removeByOrgIds(List<Long> orgIds) {
        return CollUtil.isNotEmpty(orgIds) && SqlHelper.retBool(super.baseMapper.deleteByOrgIds(orgIds));
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public List<OrgAuditVO> listByOrgId(Long orgId) {
        return super.baseMapper.selectListByOrgId(orgId);
    }

    /**
     * 查询下一个排序号.
     *
     * @param orgId 组织主键
     * @return Integer
     */
    private Integer getNextSeq(Long orgId) {
        QueryWrapper<OrgAuditDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrgAuditDO::getOrgId, orgId);
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }
}
